/**
 * 
 */
package edu.cmu.cs.webapp.ioms.ui.dialogs;

import java.util.Date;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.UserDAOImpl;
import edu.cmu.cs.webapp.ioms.models.User;

/**
 * @author Christian
 * 
 */
public class LoginDialog extends TitleAreaDialog {
	private Text _usrTxt;
	private Text _pwdTxt;
	private Group _loginGroup;
	private boolean showDBGroup;

	public LoginDialog(Shell parentShell, boolean showDBGroup) {
		super(parentShell);
		this.showDBGroup = showDBGroup;
	}

	@Override
	protected void configureShell(Shell newShell) {
		// configure the shell title, size and position
		super.configureShell(newShell);
		Rectangle parentBounds = Display.getDefault().getPrimaryMonitor()
				.getBounds();
		newShell.setSize(400, 400);
		newShell.setText("CMU Integrated Order Management System");

		newShell.setLocation((parentBounds.width - newShell.getBounds().width)
				/ 2 + parentBounds.x, (parentBounds.height - newShell
				.getBounds().height)
				/ 2 + parentBounds.y);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		// set title
		setTitle("Admin Login");
		if (!showDBGroup) {
			setMessage("This system is in used and has been locked");

		} else {
			setMessage("Please enter the admin user name and password to login the system");

		}

		Composite dialogArea = (Composite) super.createDialogArea(parent);

		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.grabExcessHorizontalSpace = true;
		_loginGroup = new Group(dialogArea, SWT.NONE);
		_loginGroup.setText("Login");
		GridLayout gl = new GridLayout();
		gl.numColumns = 2;
		_loginGroup.setLayout(gl);
		_loginGroup.setLayoutData(gd);

		Label userName = new Label(_loginGroup, SWT.None);
		userName.setText("Admin User:");
		this._usrTxt = new Text(_loginGroup, SWT.BORDER);
		this._usrTxt.setLayoutData(gd);
		this._usrTxt.addModifyListener(new ModifyListener() {

			public void modifyText(ModifyEvent e) {
				validateInput();
			}
		});
//		this._usrTxt.setText("admin");

		Label pwdName = new Label(_loginGroup, SWT.None);
		pwdName.setText("Password:");
		this._pwdTxt = new Text(_loginGroup, SWT.BORDER | SWT.PASSWORD);
		this._pwdTxt.setLayoutData(gd);

		// new Label(dialogArea, SWT.None);
		// if (showDBGroup) {
		// SWTUtils.createSpacer(dialogArea, 2);
		// createDBGroup(dialogArea);
		// }

		return dialogArea;
	}

	protected void validateInput() {
		boolean valid = true;
		if (this._usrTxt == null) {
			return;
		}

		if (this._usrTxt.getText() == null
				|| this._usrTxt.getText().length() == 0) {
			valid = false;
		}

		if (!valid) {
			setErrorMessage("Admin user input cannot be empty");
			enableOKButton(false);
		} else {
			setErrorMessage(null);
			enableOKButton(true);
		}
	}

	private void enableOKButton(boolean enable) {
		Button okBtn = getButton(IDialogConstants.OK_ID);
		if (okBtn != null) {
			okBtn.setEnabled(enable);
		}
	}

	@Override
	protected void okPressed() {

		if (isValidLogin() && testConnection(false)) {

			super.okPressed();
		}
	}

	private boolean testConnection(boolean prompt) {

		if (!showDBGroup) {
			return true;
		}

		//
		// try {
		// ProgressManager.getInstance().run(false, false,
		// new IRunnableWithProgress() {
		//
		// public void run(IProgressMonitor monitor)
		// throws InvocationTargetException,
		// InterruptedException {
		// if (factory != null
		// && factory instanceof MYSQLFactory) {
		// try {
		// ((MYSQLFactory) factory).openConnection(
		// getConnectionURL(), getDBUser(),
		// getDBPassword());
		//
		// } catch (SQLException e) {
		// setErrorMessage(e.getLocalizedMessage());
		// }
		// }
		// }
		// });
		// } catch (InvocationTargetException e) {
		// e.printStackTrace();
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		//
		// if (factory != null && factory.getConnection() != null) {
		// if (prompt) {
		// Display.getDefault().syncExec(new Runnable() {
		//
		// public void run() {
		// MessageDialog.openInformation(null, "Test Connection",
		// "Ping success!");
		// }
		// });
		// }
		// setErrorMessage(null);
		// return true;
		// }
		//
		// return false;

		// TODO
		return true;

	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		// create OK and Cancel buttons by default
		if (showDBGroup) {
			super.createButtonsForButtonBar(parent);
		} else {
			createButton(parent, IDialogConstants.OK_ID, "Unlock", true);
		}
	}

	@Override
	public boolean close() {

		if (isValidLogin()) {
			return super.close();
		}

		return false;
	}

	/**
	 * @return
	 */
	private boolean isValidLogin() {
		boolean status = true;
		String login = this._usrTxt.getText().trim();
		User usr = null;
		String errorMessage = null;
		try {
			usr = new UserDAOImpl().findUser(login);
		} catch (DataAccessException e) {
		}

		if (status && usr == null) {
			errorMessage = "User not exist";
			status = false;
		}

		if (status && !usr.getPassword().equals(this._pwdTxt.getText())) {
			errorMessage = "Invalid password";
			status = false;
		}

		if (status) {
			usr.setLast_login(new Date());
			RWT.getSessionStore().setAttribute("uid", usr);
		} else {
			setErrorMessage(errorMessage);
		}
		return status;
	}

}
